package com.watson.mq;

import android.os.AsyncTask;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.watson.MyApp;
import com.watson.utils.LogUtils;
import com.watson.utils.NotificationHelper;
import com.watson.utils.SPUtils;

import java.io.IOException;
import java.util.Map;

/**
 * 功能:MQ接收消息工具类
 */
public class ReceiveMessageTask extends AsyncTask<Void, String, Void> {
    @Override
    protected Void doInBackground(Void... voids) {
        RabbitMQHelper helper = new RabbitMQHelper();
        ConnectionFactory factory = helper.getConnectionFactory();
        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) {
            String queueName = "wms_push_queue";  //队列
            String exchangeName = "wms_push_exchange";//交换机
            String routingKey = SPUtils.get(MyApp.getContext(), "U_Id", "") + "";//路由key
            // 声明交换机
            channel.exchangeDeclare(exchangeName, "direct", true);
            // 声明队列
            channel.queueDeclare(queueName, true, false, false, null);
            // 绑定交换机和队列
            channel.queueBind(queueName, exchangeName, routingKey);
            // 定义消费者
            channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body, "UTF-8");
                    LogUtils.e("RabbitMQ", " [x] Received '" + message + "'");

                    // 手动确认消息
//                    channel.basicAck(envelope.getDeliveryTag(), false);

                    // 在这里，可以添加处理消息的代码
                    onProgressUpdate(message);
                    //  Log.i("这是啥",message);
                }
            });

            // 保持频道打开以侦听消息。
            synchronized (this) {
                this.wait();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(String... messages) {
        // 将您的UI与接收到的消息联合使用
        //type  类型  1撤单（其他的暂时没有）
        //no  发运单号，根据no调用获取明细接口，
        //billno   erp单号，暂时没啥用
        //msg   通知栏title内容
        //{"type":1,"no":"9000001","billno":"2322-99072900009","msg":"2322-99072900009撤单"}
        LogUtils.e("RabbitMQ", " [x] Processed '" + messages[0] + "'");
        LogUtils.e("RabbitMQ", "接收的消息为" + messages[0]);
        LogUtils.e("RabbitMQ", "接收的消息为------" + messages[0].contains("billno"));
        if (messages[0].contains("billno")) {
            Map data = JSON.parseObject(messages[0] + "", Map.class);
            LogUtils.e("RabbitMQ", "data:" + data.toString());
            LogUtils.e("RabbitMQ", "data---:" + data.isEmpty());
            if (!data.isEmpty()) {
                String title = data.get("type").toString().equals("1") ? "撤单提醒" : "消息提醒";
                if (data.get("type").toString().equals("1")) {
                    NotificationHelper.sendNotification(MyApp.getContext(), title, data.get("msg") + "", data.get("no") + "");
                } else {
                    NotificationHelper.sendNotification2(MyApp.getContext(), title, data.get("msg") + "", data.get("no") + "");
                }
            }
        }
    }
}
